package customerController

import (
	"WEB/models"
	"fmt"
	"github.com/astaxie/beego/orm"
	"html/template"
)

type SearchController struct {
	BaseController
}

// @router /customer/search [get]
func (this *SearchController) SearchGood() {
	name := this.GetString("title")
	var goods []models.Goods
	var rows int64
	if name == "" {
		goods = models.SelectAllSellGood()
	} else {
		goods = models.SelectAllGoodByName(name)
	}
	for i, v := range goods {
		goods[i].GoodStoreName = models.GetStoreByPrimarkKey(v.GoodStoreId).StoresName
	}
	rows = int64(len(goods))
	this.Data["Title"] = name
	this.Data["Number"] = rows
	this.Data["SystemType"] = models.GetSystemType()
	this.Data["Goods"] = goods
	this.TplName = "customer/commodity.html"
}

// @router /customer/goods [get]
func (this *SearchController) GetGood() {
	i, e := this.GetInt("MenuId")
	var goods []models.Goods
	newOrm := orm.NewOrm()
	var sql string
	var rows int64
	if e != nil {
		sql = ` select *
				from  goods where good_is_sell = 1 `
		newOrm.Raw(sql).QueryRows(&goods)
	} else {
		sql = ` select *
				from  goods
				where good_is_sell = 1 and good_kind_id in( select goods_kind_id
                                       from goods_kind
										where system_kind_id = ?)	`
		rows, e = newOrm.Raw(sql, i).QueryRows(&goods)
		if e != nil {
			panic(e)
		}
	}
	for i, v := range goods {
		goods[i].GoodStoreName = models.GetStoreByPrimarkKey(v.GoodStoreId).StoresName
	}
	fmt.Println(goods)
	this.Data["Number"] = rows
	this.Data["SystemType"] = models.GetSystemType()
	this.Data["Goods"] = goods
	this.TplName = "customer/commodity.html"
}

// @router /customer/goodDetail [get]
func (this *SearchController) GetDetail() {
	goodId, e := this.GetInt("id")
	if e != nil {
		panic(e)
	}
	orm := orm.NewOrm()
	var good models.Goods
	sql := models.QueryByPrimaryKey(good)
	e = orm.Raw(sql, goodId).QueryRow(&good)
	if e != nil {
		this.Redirect("error?info="+e.Error(), 302)
		return
	}
	this.Data["Good"] = good
	this.TplName = "customer/details.html"
}

// @router /customer/searchByKind [get]
func (this *SearchController) GetGoodByKind() {
	kindId, e := this.GetInt("kindId")
	if e != nil {
		panic(e)
	}
	storeId, e := this.GetInt("storeId")
	if e != nil {
		panic(e)
	}

	store := models.GetStoreByPrimarkKey(storeId)
	this.Data["StoresLoopPic1"] = template.URL(store.StoresLoopPic1)
	this.Data["StoresLoopPic2"] = template.URL(store.StoresLoopPic2)
	this.Data["StoresLoopPic3"] = template.URL(store.StoresLoopPic3)
	this.Data["Store"] = store

	goods := models.SeletAllSellGoodByKindId(kindId, storeId)
	this.Data["Number"] = len(goods)
	this.Data["SystemType"] = models.GetSystemType()
	this.Data["Goods"] = goods
	kinds, _ := models.GetAllParentGoodKindByStoreId(storeId)
	this.Data["GoodsKind"] = kinds
	this.TplName = "customer/store.html"
}
